import * as Phaser from "phaser";

type AttentionCallback = (velocity: number) => void;

export class AttentionSystem {

    private scene: Phaser.Scene;
    private currentTimer: Phaser.Time.TimerEvent | null;
    private readonly checkInterval: number;
    private readonly levels: any;
    private declare attention: number;
    private declare readonly callback: AttentionCallback;

    constructor(scene: Phaser.Scene, callback: AttentionCallback) {
        this.scene = scene;
        this.callback = callback;
        this.checkInterval = 100; // 检测间隔(ms)
        this.currentTimer = null;

        // 注意力等级配置表
        const dpr = window.devicePixelRatio || 1;
        this.levels = [
            {min: 0, max: 39, delay: 1500, gravity: 200 * dpr},
            {min: 40, max: 50, delay: 1500, gravity: 220 * dpr},
            {min: 51, max: 60, delay: 1500, gravity: 240 * dpr},
            {min: 61, max: 70, delay: 1450, gravity: 260 * dpr},
            {min: 71, max: 80, delay: 1450, gravity: 280 * dpr},
            {min: 81, max: 90, delay: 1400, gravity: 300 * dpr},
            {min: 91, max: 100, delay: 1400, gravity: 320 * dpr}
        ];
    }

    updateAttention(attention: number) {
        this.attention = attention;
    }

    // 启动检测系统
    start() {
        this.scheduleCheck();
    }

    // 调度下一次检测
    private scheduleCheck() {
        this.currentTimer = this.scene.time.delayedCall(
            this.checkInterval,
            () => this.checkAttention(),
            [], this
        );
    }

    // 获取当前注意力等级
    private getCurrentLevel(attentionValue: number) {
        return this.levels.find((level: any) =>
            attentionValue >= level.min && attentionValue <= level.max
        ) || this.levels[0]; // 默认返回最低等级
    }

    // 核心检测逻辑
    private async checkAttention() {
        const attention = this.getAttentionValue(); // 获取实时注意力值
        const level = this.getCurrentLevel(attention);

        // 应用重力参数
        this.callback(level.gravity);

        // 取消之前的延迟
        if (this.currentTimer) this.currentTimer.remove();

        // 等待指定时间后继续检测
        await new Promise(resolve => {
            this.currentTimer = this.scene.time.delayedCall(
                level.delay,
                resolve,
                [], this
            );
        });

        this.scheduleCheck(); // 重启检测循环
    }

    // 获取注意力值（需替换为实际数据源）
    private getAttentionValue() {
        // return Math.floor(Math.random() * 101); // 模拟0-100的值
        return this.attention;
    }
}